<template>
    <el-dialog width="600" :title="$t('Order.modifyThePrice')" v-model="visible" :close-on-click-modal="false"
        @close="closeDia" draggable>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
            <el-form-item prop="reduceAmount" :label="$t('Order.reduceAmount')">
                <el-input v-model="form.reduceAmount" :placeholder="$t('Order.inputReduceAmountTip')" clearable
                    show-word-limit :maxlength="10" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
                <el-button @click="onSubmit" type="primary" :disabled="loading">{{ $t('common.confirmButtonText')
                }}</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { changePriceAPI, ChangePriceParams } from '/@/api/bizs/Order';
import { useMessage, useMessageBox } from "/@/hooks/message";
// 定义i18n
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const loading = ref(false)
const visible = ref(false)
const dataFormRef = ref()
const orderAmount = ref<string | number>('')
const prodId = ref<string | number>("")
const form = reactive<ChangePriceParams>({
    reduceAmount: ""
})
const emit = defineEmits(['refresh'])
const dataRules = ref({
    reduceAmount: [
        { required: true, message: t('Order.noNumber'), trigger: 'blur' },
        {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: t("Order.maximum"),
            trigger: 'blur'
        }
    ]
})

const closeDia = () => {
    nextTick(() => {
        dataFormRef.value?.resetFields();
    });
}

const onSubmit = async () => {




    const valid = await dataFormRef.value.validate().catch(() => { });
    if (!valid) return false
    if (Number(orderAmount.value) < Number(form.reduceAmount)) {
        useMessage().error(t('Order.tpisPrice'))
        return
    }

    try {
        await useMessageBox().confirm(t('Order.confirmChangePrice'))
    } catch {
        return;
    }

    form.reduceAmount = Number(form.reduceAmount)
    try {
        loading.value = true;

        await changePriceAPI(prodId.value, form)
        visible.value = false;
        emit('refresh')
    } catch (err: any) {
        useMessage().error(err.msg);
    } finally {
        loading.value = false;

    }

}


defineExpose({
    prodId,
    visible,
    orderAmount
})
</script>